package java_class_work.week07;

import java.sql.*;
import java.util.ResourceBundle;

/**
 * @Author Tiam
 * @Date 2022/10/24 13:24
 * @Description: JDBC 工具类
 */
public class JDBCUtils {

    private static Connection conn = null;
    private static Statement state = null;
    private static PreparedStatement prestate = null;

    public static Connection getConnection(){
        // 获取配置文件
        ResourceBundle bundle = ResourceBundle.getBundle("java_class_work\\week07\\jdbc");
        String driverClass = bundle.getString("driverClass");
        String url = bundle.getString("url");
        String username = bundle.getString("username");
        String password = bundle.getString("password");

        try {
            // 1. 注册驱动
            Class.forName(driverClass);

            // 2. 获取连接
            conn = DriverManager.getConnection(url, username, password);

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

    /**
     * 获取数据库对象
     *
     * @return
     */
    public static Statement getStatement() {
        try {
            state =  getConnection().createStatement();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return state;
    }


    /**
     * 释放资源
     */
    public static void close() {
        // 6. 释放资源
        try {
            if(state!=null) state.close();
            if(conn!=null) conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
